import logging
from utils.singleton_base import SingletonBase
from google.appengine.ext.webapp import RequestHandler

class OnlineUser():
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.cmdQueue = []
        self.cards = []
        self.state = 0 # user_state.INIT

    def addCmd(self, cmd, args):
        self.cmdQueue.append({'cmd': cmd, 'args': args})

    def addCard(self, card):
        self.cards.append(card)
        self.cards.sort()

    def setState(self, state):
        self.state = state

class OnlineUserList(RequestHandler, SingletonBase):
    onlineUser = {}
    readyUser = 0

    def getAll(self):
        return list(self.onlineUser.itervalues())

    def genId(self):
        return str(len(self.onlineUser))

    def addUser(self, uid, onlineUser):
        self.onlineUser.update({uid: onlineUser})

    def getUser(self, key):
        return self.onlineUser[key]

    def addCard(self, uid, card):
        self.onlineUser[uid].addCard(card)

    def addCmd(self, uid, cmd, args):
        self.onlineUser[uid].addCmd(cmd, args)

    def broadcastCmd(self, cmd, args, except_uid=None):
        for user in self.onlineUser.itervalues():
            if user.id != except_uid:
                user.addCmd(cmd, args)

    def setUserState(self, uid, state):
        self.onlineUser[uid].setState(state)
        self.readyUser += 1
        return self.readyUser

    def get(self):
        u_id = self.request.get('u_id')
        logging.critical(u_id)
        cmdList = []
        import thread
        lock = thread.allocate_lock()
        lock.acquire()
        _cmdList = self.onlineUser[u_id].cmdQueue
        while len(_cmdList):
            cmdList.insert(0, _cmdList.pop())
        lock.release()
        if len(cmdList):
            logging.critical(cmdList)

        self.response.out.write(cmdList)
